import Vue from 'vue'
import show from "@/common/show.js"

/**
 * 封装 uni request 
 * @param {*} url 
 * @param {*} data 
 * @param {*} method 
 * @param {*} loading 
 */
function request(url, data = {}, method = "GET", loading = true) {
	let baseUrl = "http://127.0.0.1:8080"
	return new Promise(function(resolve, reject) {
		let header = {
			"Accept": "application/json",
		};
		if (method == 'POST') {
			header['content-type'] = 'application/x-www-form-urlencoded'
		}
		if (uni.getStorageSync("token")) {
			header['Authorization'] = 'Bearer ' + uni.getStorageSync("token")
		}
		if (loading) {
			show.loading()
		}
		uni.request({
			url: baseUrl + url,
			data: data,
			method: method,
			header: header,
			success: (res) => {
				if (res.statusCode == 200) {
					if (res.data.code == 0) {
						resolve(res.data);
					} else {
						reject(res.data)
						show.toast({
							title: res.data.msg,
							icon: 'none'
						})
						show.hideLoading();
					}
				} else {
					if (res.statusCode == 401) {
						show.toast({
							title: res.message,
							icon: 'none'
						})
						setTimeout(() => {
							uni.removeStorageSync('token');
							uni.reLaunch({
								url: '/pages/index/index'
							});
						}, 1500)
						show.hideLoading();
					} else {
						reject(res.data)
						show.toast({
							title: 'Network Error',
							icon: 'none'
						})
						uni.hideLoading();
					}
				}
			},
			fail: (err) => {
				console.log("网络请求失败", err)
				reject(err)
			},
			complete: () => {
				if (loading == true)
					uni.hideLoading();
			}
		})
	});
}
export default request
